package com.company.nettyT.codec;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufEncoder;

public class NettyClient {
    public static void main(String[] args) throws Exception {
        //创建一个线程组
        EventLoopGroup group = new NioEventLoopGroup();
        //创建一个客户端启动助手
        Bootstrap b = new Bootstrap();
        //配置
        b.group(group) //设置线程组
                .channel(NioSocketChannel.class) //配置客户端使用的通道实现类
                .handler(new ChannelInitializer<SocketChannel>() {//创建一个通道初始化对象
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast("encoder",new ProtobufEncoder());
                        socketChannel.pipeline().addLast(new NettyClientHandler());


                    }
                });
        System.out.println("client is ready......");
        //连接服务器端 connect方法是异步的 sync方法是同步阻塞的
        ChannelFuture cf = b.connect("127.0.0.1", 9999).sync();


        //关闭连接
        cf.channel().closeFuture().sync();//关闭通道
        //关闭组
        group.shutdownGracefully();


    }

}
